package cn.edu.lzzy.services.Impl;

import cn.edu.lzzy.dao.UserRepository;
import cn.edu.lzzy.entities.User;
import cn.edu.lzzy.dao.UserProjection;
import cn.edu.lzzy.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.UUID;

/**
 * 用户业务层实现
 */

@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    @Override
    public User register(User user){
        return userRepository.saveAndFlush(user);
    }

    @Override
    public String getSalt(String userName) {
        List<UserProjection> users = userRepository.findUserByUserName(userName);
        if(ObjectUtils.isEmpty(users)){
            return "";
        }
        UserProjection user = users.get(0);
        if(ObjectUtils.isEmpty(user)){
            return "";
        }
        String salt = user.getSalt();
        return ObjectUtils.isEmpty(salt)? "" : salt;
    }

    @Override
    public User checkedUser(String userName, String password) {
        return userRepository.findUserByUserNameAndPassword(userName, password);
    }

    //============应用场景：用户列表，获取用户数据==============
    @Override
    public List<User> getUsers() {
        return userRepository.findAllByOrderByUpdateTimeDesc();
    }

    @Override
    public List<User> getUsers(int page, int size) {
        return userRepository.findAllByOrderByUpdateTimeDesc(PageRequest.of(page, size));
    }

    @Override
    public Integer count() {
        return userRepository.countAllBy();
    }


    /**
     * 获取申请成为教师的数据
     */
    @Override
    public List<User> getByApplyTeacher(boolean applying) {
        return userRepository.findUserByApplyTeacherOrderByUpdateTimeDesc(applying);
    }
    //=======应用场景：模糊查找=======
    @Override
    public List<User> search(String keyword) {
        return userRepository.findByQuery(keyword);
    }
    /**
     * 审批教师申请
     */
    // @Transactional注解在代码执行出错的时候能够进行事务的回滚
    //有点问题
    @Transactional(rollbackFor = Exception.class)
    @Override
    public User approveTeacher(UUID id) {
        User user = userRepository.findById(id).orElse(null);
        if (!ObjectUtils.isEmpty(user)) {
            user.setApplyTeacher(true);
            user.setType(User.TYPE_TEACHER);
            return userRepository.saveAndFlush(user);
        }
        return null;
    }

    /**
     * 拒绝申请成为教师的申请
     */
    // @Transactional注解在代码执行出错的时候能够进行事务的回滚
    @Transactional(rollbackFor = Exception.class)
    @Override
    public User declineTeacher(UUID id) {
        User user = userRepository.findById(id).orElse(null);
        if (!ObjectUtils.isEmpty(user) && user.getType() != User.TYPE_STUDENT) {
            user.setApplyTeacher(false);
            return userRepository.saveAndFlush(user);
        }
        return null;
    }
    /**
     * 禁用用户，
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public User banUser(UUID id) {
        User user = userRepository.findById(id).orElse(null);
        if (!ObjectUtils.isEmpty(user) && user.getType() != User.TYPE_ADMIN) {
            user.setType(User.TYPE_BANNED);
            return userRepository.saveAndFlush(user);
        }
        return null;
    }

    /**
     * 根据id查找用户（精确查找）
     */
    @Override
    public User getById(UUID id) {
        return userRepository.findById(id).orElse(null);
    }

    //=======应用场景:用户登录======
    @Override
    public boolean isUserNameOccupied(String userName){
        return userRepository.countByUserName(userName)>0;//userRepository.countByUserName(userName)>0 ? true:false 的简写形式
    }

}
